import datetime
from django.utils.deprecation import MiddlewareMixin
from app01 import models
from django.conf import settings
from django.shortcuts import redirect

class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):

        tracer_obj = Tracer()
        user_id = request.session.get('user_id', 0)
        user_obj = models.Userinfo.objects.filter(id=user_id).first()
        tracer_obj.user = user_obj
        request.tracer = tracer_obj
        # 白名单：没有登录都可以访问的url
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not request.tracer.user:
            return redirect('app01:login')

        # 登录成功之后，访问后台管理时：获取当前用户所拥有的额度
            # 获取当前用户的最近交易记录
        transaction_obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        if transaction_obj.end_datetime and transaction_obj.end_datetime < current_datetime:
            # 过期
            transaction_obj = models.Transaction.objects.filter(user=user_obj, status=2, price_policy=1).first()
        tracer_obj.price_policy = transaction_obj.price_policy
        request.tracer = tracer_obj

    def process_view(self, request, view, args, kwargs):
        # 判断URL是否是以app01/manage/开头，如果是则判断项目ID是否我创建 or 参与
        if not request.path_info.startswith('/app01/manage/'):
            return
        project_id = kwargs.get('project_id')
        # 是否是我创建的
        project_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_obj:
            # 是我创建的项目，就让他通过
            request.tracer.project = project_obj
            return
        # 是否是我参与的
        project_user_obj = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_obj:
            # 是我参与的项目
            request.tracer.project = project_user_obj.project
            return
        return redirect('app01:project')